//
//  KLViewModel.m
//  KoalaUtilKit
//
//  Created by Tommy on 15/1/4.
//  Copyright (c) 2015年 Alibaba-inc.com. All rights reserved.
//

#import "KLViewModel.h"
#import "KLCacheService.h"
#import "KLModel.h"

@interface KLViewModel()

@property(nonatomic,strong) NSString   *cacheKey;

@end

@implementation KLViewModel

- (instancetype)init{
//    NSAssert(0, @"can not call this method");
    if(self = [self initWithModel:nil]){
        
    }
    return self;
}
- (instancetype)initWithModelCls:(Class)modelCls{
    if(self = [self initWithModel:[[modelCls alloc]init]]){
    }
    return self;
}
- (instancetype)initWithModel:(KLModel*)model{
    if(self = [super init]){
        self.model = model;
        _cacheKey = NSStringFromClass([self class]);
    }
    
    return self;
}
- (instancetype)initWithService:(id)service andModelCls:(Class)modelCls{
    if(self = [self initWithModel:[[modelCls alloc]init]]){
        _modelService = service;
    }

    return self;
}


- (RACCommand*)cacheToDisk{
    @weakify(self);
    return [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            @strongify(self);
            [[[KLCacheService setObject:self.model forKey:self.cacheKey] subscribeOn:[RACScheduler scheduler]] subscribe:subscriber];
            return nil;
        }];
        
    }];
    
}
- (RACCommand*)loadFromDisk{
    @weakify(self);
    return [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            @strongify(self);
            
            [[KLCacheService objectForKey:self.cacheKey] subscribeNext:^(id<NSCoding> model) {
                [self parseModel:model];
                [subscriber sendNext:model];
                [subscriber sendCompleted];
            }completed:^{
                [subscriber sendCompleted];
            }];
            return nil;
        }];
    }];
}

- (RACCommand*)removeFromDisk{
    @weakify(self);
    return [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            @strongify(self);
            
            [[KLCacheService removeObjectForKey:self.cacheKey] subscribeCompleted:^{
                [subscriber sendCompleted];
            }];
            return nil;
        }];
    }];
}

- (void)parseModel:(id<NSCoding>) model{
    //    NSAssert(0, @"should override the parseModel: method");
}







@end
